package com.smart.tool.extension.repository;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

import com.google.common.collect.Lists;
import com.smart.tool.extension.SenceParam;
import com.smart.tool.extension.model.ExtensionOperation;
import com.smart.tool.extension.model.ExtensionSence;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.CollectionUtils;

/**
 * 扩展点管理类
 */
public class ExtensionRepositoryImpl implements IExtensionRepository {


    private static final Logger LOGGER = LoggerFactory.getLogger(ExtensionRepositoryImpl.class);
    /**
     * 扩展点管理缓存，存储扩展点唯一性key和对应的对象
     */
    private Map<String, ExtensionOperation> extensionCacheMap = new ConcurrentHashMap<>();


    /**
     *
     */
    private Map<String, List<ExtensionOperation>> sceneCacheMap = new ConcurrentHashMap<>();

    @Override
    public <T> Collection<T> getExtensionList(Class<T> searchClass) {
        if (sceneCacheMap.isEmpty()) {
            return Lists.newArrayList();
        }


        List<T> objects = Lists.newArrayList();
        sceneCacheMap.forEach((k, v) -> {
            for(ExtensionOperation operation : v){
                if(operation.filterOperation(searchClass)){
                    objects.add((T)operation.getiExtension());
                }
            }
        });
        return objects;
    }

    @Override
    public synchronized void loadExtension(Object extension, ExtensionSence extensionSence) {
        ExtensionOperation operation = buildExtensionOperation(extensionSence);
        operation.setIExtension(extension);
        String uniqueKey = operation.uniqueUseCaseKey();
        ExtensionOperation extensionOperation = extensionCacheMap.get(uniqueKey);
        if (extensionOperation != null) {
            LOGGER.warn("[ExtensionRepositoryImpl-loadExtension] duplicate extension ,key = {}", uniqueKey);
            throw new RuntimeException("duplicate extension ,key = " + uniqueKey);
        }
        extensionCacheMap.put(uniqueKey, operation);

        String senceKey = operation.uniqueSenceKey();
        List<ExtensionOperation> operationList = sceneCacheMap.get(senceKey);
        if (CollectionUtils.isEmpty(operationList)) {
            operationList = new ArrayList<>();
            sceneCacheMap.put(senceKey, operationList);
        }
        //根据order从大到小进行排序
        operationList.sort((o1, o2) -> o2.getOrder() - o1.getOrder());
        operationList.add(operation);
    }

    private ExtensionOperation buildExtensionOperation(ExtensionSence extensionSence) {
        ExtensionOperation operation = new ExtensionOperation();
        operation.setClazz(extensionSence.getClazz());
        operation.setUseCase(extensionSence.getUseCase());
        operation.setSence(extensionSence.getSence());
        operation.setOrder(extensionSence.getOrder());
        operation.setSuperClasses(extensionSence.getSuperClasses());
        operation.setInterfaceClasses(extensionSence.getInterfaceClasses());
        return operation;
    }


    @Override
    public Object getExtension(SenceParam senceParam,Class<?> searchClass) {
        String senceKey = senceParam.uniqueSenceKey();
        List<ExtensionOperation> realOperationList = sceneCacheMap.get(senceKey);
        if (CollectionUtils.isEmpty(realOperationList)) {
            return null;
        }
        List<ExtensionOperation> realOperation = realOperationList.stream()
            .filter(operation -> operation.filterOperation(searchClass)).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(realOperationList)) {
            return null;
        }
        if(senceParam.getOrder()!=null){
            realOperation = realOperation.stream().filter(operation -> operation.getOrder() == senceParam.getOrder()).collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(realOperationList)) {
            return null;
        }
        realOperation.sort((o1, o2) -> o2.getOrder() - o1.getOrder());

        return realOperation.get(0).getiExtension();
    }

    @Override
    public Collection<Object> getExtensionList(SenceParam senceParam, Class<?> searchClass) {
        String senceKey = senceParam.uniqueSenceKey();
        List<ExtensionOperation> realOperationList = sceneCacheMap.get(senceKey);
        if (CollectionUtils.isEmpty(realOperationList)) {
            return Lists.newArrayList();
        }
        List<ExtensionOperation> realOperation = realOperationList.stream()
            .filter(operation -> operation.filterOperation(searchClass)).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(realOperationList)) {
            return Lists.newArrayList();
        }
        if(senceParam.getOrder()!=null){
            realOperation = realOperation.stream().filter(operation -> operation.getOrder() == senceParam.getOrder()).collect(Collectors.toList());
        }
        if (CollectionUtils.isEmpty(realOperationList)) {
            return Lists.newArrayList();
        }
        realOperation.sort((o1, o2) -> o2.getOrder() - o1.getOrder());
        return realOperation.stream().map(ExtensionOperation::getiExtension).collect(Collectors.toList());
    }
}
